# -*- coding: UTF-8 -*-
'''
Created on 11.06.2014

@author: MathiasAr
'''

import Image, ImageColor
import os, math
import ImageHelper
from ImageHelper import AutoOrientImage, CropResize
from random import random


def MakeJpegMatrix(columns, rows, sizeX, sizeY, sourceFolder, fromScale, toScale, fromAngle, toAngle, fromAlpha, toAlpha, backgroundImage=None):
    """
    sizeTolerance = targetPicture size plus/minus percent (0 means no variation)
    fromAngle, toAngle = rotate pictures between both angles (0 means no rotation)
    """
    fromScale = float(fromScale)
    toScale = float(toScale)
    if (columns == 0 or rows == 0 or sizeX == 0 or sizeY == 0): return None
    files = []
    
    if os.path.isdir(sourceFolder):
        for f in os.listdir(sourceFolder):
            fname = sourceFolder + os.path.sep + f
            ext = os.path.splitext(f)[-1]
            if (os.path.isfile(fname) and (ext.lower() == ".jpg" or ext.lower() == ".jpeg" or ext.lower() == ".png")):
                files.append(fname)
                pass
            pass
        pass
    
    if len(files) <= 0: return None
    
    # canvas size 
    canvasX = columns * sizeX
    canvasY = columns * sizeY
    
    target = Image.new("RGBA", (canvasX, canvasY), (0, 0, 0, 0))
    
    # paste background image if given
    if (os.path.isfile(backgroundImage)):
        bkgIm = Image.open(backgroundImage, "r")
        bkgIm = AutoOrientImage(bkgIm, ImageHelper.GetImageOrientation(backgroundImage))
        bkgIm = CropResize(bkgIm, target.size)
        target.paste(bkgIm)
    
    # fill matrix table
    matrixTable = []
    for r in range(rows):
        for c in range(columns):
            matrixTable.append((c, r))
            pass
        pass
    
    i = 0
    for f in files:
        if len(matrixTable) == 0: break
        
        im = Image.open(f, "r")
        if not im: continue
        
        # calculate alpha
        alpha = int(random() * float(toAlpha - fromAlpha)) + fromAlpha
        
        # append an alpha channel
        im.putalpha(alpha)
    
        # calculate the target picture ration
        tol = (random() * (toScale - fromScale) + fromScale) / 100.0
        targetX = int(sizeX + sizeX * tol);
        targetY = int(sizeY + sizeY * tol);
        
        # automatically orient the source picture
        exifOrientation = ImageHelper.GetImageOrientation(f) * 90
        im = AutoOrientImage(im, exifOrientation)
        
        # resize picture
        im = CropResize(im, (targetX, targetY))
        
        # set the randomized angle
        angleRange = toAngle - fromAngle;
        srcAngle = random() * float(angleRange) + fromAngle;
        
        # rotate image
        im = im.rotate(srcAngle, Image.NEAREST, 1)
        
        c, r = matrixTable.pop(int(round(random() * float(len(matrixTable) - 1))))
        
        posX = ((c * sizeX) + (sizeX - im.size[0]) / 2)
        posY = ((r * sizeY) + (sizeY - im.size[1]) / 2) 
        target.paste(im, (posX, posY), im)
        
        # count up
        i += 1
        pass
    
    print "Filled matrix with %s picture(s) (given pictures: %s)" % (columns * rows, len(files))
    return target


if __name__ == '__main__':
    im = MakeJpegMatrix(3, 3, 64, 48, u"C:\\Users\\mathiasar\\Desktop\\Föteli", -20, 0, -20, 20, 200, 255, u"C:\\Users\\mathiasar\\Pictures\\MaRaBeJuMa.jpg")
    if (im):
        im.save(u"C:\\Temp\\matix.png")
    pass
